package thesis.filesharing.web.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import thesis.filesharing.bo.SubjectBO;
import thesis.filesharing.resources.Constants;
import thesis.filesharing.web.viewmodel.CreateSubjectViewModel;

public class CreateSubjectValidator implements Validator {
	
	@Autowired
	private SubjectBO subjectBO;
	
	@Override
	public boolean supports(Class<?> clazz) {
		return CreateSubjectViewModel.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "subjectId", "subjectId.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "subjectName", "subjectName.required");
		
		CreateSubjectViewModel model = (CreateSubjectViewModel) target;
		
		if (model.getSubjectId() != null && model.getSubjectId().length() > 0) {
			Pattern subjectIdPattern = Pattern.compile(Constants.SUBJECT_ID_PATTERN, Pattern.CASE_INSENSITIVE);
			Matcher subjectIdMatcher = subjectIdPattern.matcher(model.getSubjectId());
			if (!subjectIdMatcher.matches()) {
				errors.rejectValue("subjectId", "subjectId.incorrectFormat");
			}
		}
		
		if (!errors.hasErrors()) {
			if (subjectBO.findSubjectById(model.getSubjectId()) != null) {
				errors.reject("subjectId.exists");
			}
		}
	}
}
